package com.yangrong.newsservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.yangrong.common.utils.R;
import com.yangrong.newsservice.dao.TbArticlesDao;
import com.yangrong.newsservice.entity.*;
import com.yangrong.newsservice.feign.ThirdServiceFeignService;
import com.yangrong.newsservice.service.TbArticleLabelService;
import com.yangrong.newsservice.service.TbArticlesCarouselService;
import com.yangrong.newsservice.service.TbArticlesService;
import com.yangrong.newsservice.service.TbFlashArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangrong.common.utils.PageUtils;
import com.yangrong.common.utils.Query;


@Service("tbArticlesService")
public class TbArticlesServiceImpl extends ServiceImpl<TbArticlesDao, TbArticlesEntity> implements TbArticlesService {

    @Autowired
    private ThirdServiceFeignService thirdServiceFeignService;

    @Autowired
    private TbArticleLabelService tbArticleLabelService;

    @Autowired
    private TbArticlesCarouselService tbArticlesCarouselService;

    @Autowired
    private TbFlashArticlesService tbFlashArticlesService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TbArticlesEntity> page = this.page(
                new Query<TbArticlesEntity>().getPage(params),
                new QueryWrapper<TbArticlesEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveArticle(TbArticlesEntity entity) {
        // 根据用户名取得用户id
        if (entity.getUserName() != null && !entity.getUserName().equals("")) {
            String userId = stringRedisTemplate.opsForValue().get("userId:" + entity.getUserName());
            entity.setAuthor(Integer.parseInt(userId));
        }
        // 设置提交时间
        entity.setCreateTime(new Date());
        // 设置审核状态 -> 审核中
        entity.setAuditStatus(1);
        // 文章内容上传OSS对象存储
        R uploadStringResult = thirdServiceFeignService.uploadString(entity.getContent());
        // 取得内容存储路径
        String savePath = (String) uploadStringResult.get("articleSavePath");
        entity.setArticleSavePath(savePath);
        // 处理文章编辑过程中上传的冗余图片
        new Thread() {
            @Override
            public void run() {
                if (entity.getAvatarImageList().length != 0) {
                    Arrays.stream(entity.getAvatarImageList()).forEach(item -> {
                        if (!entity.getContent().contains(item)) {
                            Map<String, Object> params = new HashMap<>();
                            params.put("objectName", item);
                            thirdServiceFeignService.delete(params);
                        }
                    });
                }
            }
        }.start();
        // 文章信息存库
        baseMapper.insert(entity);
    }

    @Override
    public List<TbArticlesEntity> getArticleList(Map<String, Object> params) {
        List<TbArticlesEntity> list = new ArrayList<>();

        String type = (String) params.get("type");
        String label = (String) params.get("label");

        list = baseMapper.getArticleList(type, label);

        List<TbArticleLabelEntity> labelEntityList;

        // 根据lable字段查出对应labelList返回前端
        if (list.size() > 0) {
            for (TbArticlesEntity articlesEntity : list) {
                if (articlesEntity.getLabel() != null && !"".equals(articlesEntity.getLabel())) {
                    String[] labelStr = articlesEntity.getLabel().split("\\|");
                    List<Integer> idList = new ArrayList<>();
                    Arrays.stream(labelStr).forEach(item -> {
                        if (item != null && !"".equals(item)) {
                            idList.add(Integer.parseInt(item));
                        }
                    });

                    labelEntityList = new ArrayList<>();
                    labelEntityList = tbArticleLabelService.getBaseMapper().selectBatchIds(idList);
                    articlesEntity.setLabelEntityList(labelEntityList);

                    Long time = new Date().getTime() - articlesEntity.getCreateTime().getTime();
                    if (time < 60 * 60 * 1000) {
                        articlesEntity.setArticleTime(String.valueOf(time / (1000 * 60)) + "分钟之前");
                    } else if (time < 24 * 60 * 60 * 1000) {
                        articlesEntity.setArticleTime(String.valueOf(time / (1000 * 60 * 60)) + "小时之前");
                    } else {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
                        String dateString = formatter.format(articlesEntity.getCreateTime());
                        articlesEntity.setArticleTime(dateString);
                    }
                }
            }
        }

        return list;
    }

    @Override
    public List<TbArticlesEntity> getMoreArticleList(Map<String, Object> params) {
        List<TbArticlesEntity> list = new ArrayList<>();

        String type = (String) params.get("type");
        String label = (String) params.get("label");
        Integer start = Integer.parseInt((String) params.get("start"));
        Integer getSize = 5;

        list = baseMapper.getMoreArticleType(type, label, start, getSize);

        List<TbArticleLabelEntity> labelEntityList;

        // 根据lable字段查出对应labelList返回前端
        if (list.size() > 0) {
            for (TbArticlesEntity articlesEntity : list) {
                if (articlesEntity.getLabel() != null && !"".equals(articlesEntity.getLabel())) {
                    String[] labelStr = articlesEntity.getLabel().split("\\|");
                    List<Integer> idList = new ArrayList<>();
                    Arrays.stream(labelStr).forEach(item -> {
                        if (item != null && !"".equals(item)) {
                            idList.add(Integer.parseInt(item));
                        }
                    });

                    labelEntityList = new ArrayList<>();
                    labelEntityList = tbArticleLabelService.getBaseMapper().selectBatchIds(idList);
                    articlesEntity.setLabelEntityList(labelEntityList);

                    Long time = new Date().getTime() - articlesEntity.getCreateTime().getTime();
                    if (time < 60 * 60 * 1000) {
                        articlesEntity.setArticleTime(String.valueOf(time / (1000 * 60)) + "分钟之前");
                    } else if (time < 24 * 60 * 60 * 1000) {
                        articlesEntity.setArticleTime(String.valueOf(time / (1000 * 60 * 60)) + "小时之前");
                    } else {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
                        String dateString = formatter.format(articlesEntity.getCreateTime());
                        articlesEntity.setArticleTime(dateString);
                    }
                }
            }
        }

        return list;

    }

    @Override
    public Integer getArticleListSize(Map<String, Object> params) {
        String type = (String) params.get("type");
        String label = (String) params.get("label");

        return baseMapper.getArticleListSize(type, label);
    }

    @Override
    public String getArticleContent(Map<String, Object> params) {
        String content = null;
        try {
            R r = thirdServiceFeignService.read(params);
            content = (String) r.get("content");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return content;
    }

    @Override
    public List<TbArticlesEntity> getArticleCarousel(Map<String, Object> params) {
        Map<String, Object> articleCarouselSearchMap = new HashMap<>();
        articleCarouselSearchMap.put("show_status", 1);
        List<TbArticlesCarouselEntity> carouselEntities = tbArticlesCarouselService.getBaseMapper().selectByMap(articleCarouselSearchMap);
        List<TbArticlesEntity> articlesEntityList = new ArrayList<>();
        List<Integer> articleIdList = new ArrayList<>();

        if (carouselEntities.size() > 0) {
            for (TbArticlesCarouselEntity entity : carouselEntities) {
                articleIdList.add(entity.getArticleId());
            }
        } else {
            return null;
        }

        articlesEntityList = baseMapper.selectBatchIds(articleIdList);

        List<TbArticleLabelEntity> labelEntityList;
        // 根据lable字段查出对应labelList返回前端
        if (articlesEntityList.size() > 0) {
            for (TbArticlesEntity articlesEntity : articlesEntityList) {
                if (articlesEntity.getLabel() != null && !"".equals(articlesEntity.getLabel())) {
                    String[] labelStr = articlesEntity.getLabel().split("\\|");
                    List<Integer> idList = new ArrayList<>();
                    Arrays.stream(labelStr).forEach(item -> {
                        if (item != null && !"".equals(item)) {
                            idList.add(Integer.parseInt(item));
                        }
                    });

                    labelEntityList = new ArrayList<>();
                    labelEntityList = tbArticleLabelService.getBaseMapper().selectBatchIds(idList);
                    articlesEntity.setLabelEntityList(labelEntityList);

                    Long time = new Date().getTime() - articlesEntity.getCreateTime().getTime();
                    if (time < 60 * 60 * 1000) {
                        articlesEntity.setArticleTime(String.valueOf(time / (1000 * 60)) + "分钟之前");
                    } else if (time < 24 * 60 * 60 * 1000) {
                        articlesEntity.setArticleTime(String.valueOf(time / (1000 * 60 * 60)) + "小时之前");
                    } else {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
                        String dateString = formatter.format(articlesEntity.getCreateTime());
                        articlesEntity.setArticleTime(dateString);
                    }
                }
            }
        }

        return articlesEntityList;
    }

    @Override
    public List<TbArticlesEntity> getFlashArticle(Map<String, Object> params) {
        Map<String, Object> flashArticleSearchMap = new HashMap<>();
        flashArticleSearchMap.put("show_status", 1);
        List<TbFlashArticlesEntity> flashArticlesEntities = tbFlashArticlesService.getBaseMapper().selectByMap(flashArticleSearchMap);
        List<TbArticlesEntity> articlesEntityList = new ArrayList<>();
        List<Integer> articleIdList = new ArrayList<>();

        if (flashArticlesEntities.size() > 0) {
            for (TbFlashArticlesEntity entity : flashArticlesEntities) {
                articleIdList.add(entity.getArticleId());
            }
        } else {
            return null;
        }

        articlesEntityList = baseMapper.selectBatchIds(articleIdList);

        List<TbArticleLabelEntity> labelEntityList;
        // 根据lable字段查出对应labelList返回前端
        if (articlesEntityList.size() > 0) {
            for (TbArticlesEntity articlesEntity : articlesEntityList) {
                if (articlesEntity.getLabel() != null && !"".equals(articlesEntity.getLabel())) {
                    String[] labelStr = articlesEntity.getLabel().split("\\|");
                    List<Integer> idList = new ArrayList<>();
                    Arrays.stream(labelStr).forEach(item -> {
                        if (item != null && !"".equals(item)) {
                            idList.add(Integer.parseInt(item));
                        }
                    });

                    labelEntityList = new ArrayList<>();
                    labelEntityList = tbArticleLabelService.getBaseMapper().selectBatchIds(idList);
                    articlesEntity.setLabelEntityList(labelEntityList);

                    Long time = new Date().getTime() - articlesEntity.getCreateTime().getTime();
                    if (time < 60 * 60 * 1000) {
                        articlesEntity.setArticleTime(String.valueOf(time / (1000 * 60)) + "分钟之前");
                    } else if (time < 24 * 60 * 60 * 1000) {
                        articlesEntity.setArticleTime(String.valueOf(time / (1000 * 60 * 60)) + "小时之前");
                    } else {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
                        String dateString = formatter.format(articlesEntity.getCreateTime());
                        articlesEntity.setArticleTime(dateString);
                    }
                }
            }
        }

        return articlesEntityList;
    }

}